<template>
  <div class="mall-upload">
    <el-upload
      ref="elUpload"
      action=""
      list-type="picture-card"
      :auto-upload="true"
      :file-list="nowFileList"
      :http-request="uploadBefore"
      :limit="limit"
      :multiple="multiple"
      :class="{ 'notShow' : key.length === limit }"
    >
      <i slot="default" class="el-icon-plus" />
      <div slot="file" slot-scope="{file}">
        <img v-if="filterImgType.indexOf(file.name.split('.')[file.name.split('.').length - 1]) !== -1" class="el-upload-list__item-thumbnail" :src="file.url" alt="">
        <img v-else src="../../assets/common/file.png" alt="" class="file-img">
        <div v-if="nameShow" class="file-name overflow1" :title="file.name">{{ file.name }}</div>
        <span class="el-upload-list__item-actions">
          <span
            v-if="!disabled"
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <i class="el-icon-zoom-in" />
          </span>
          <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
            <i class="el-icon-delete" />
          </span>
        </span>
      </div>
    </el-upload>
    <el-dialog v-if="dialogVisible" :visible.sync="dialogVisible" :close-on-click-modal="false" :append-to-body="true">
      <div style="text-align: center">
        <img style="width:300px;height:300px" :src="dialogImageUrl" alt="">
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { getPolicy } from '@/api/common'
export default {
  props: {
    multiple: {
      required: false,
      type: Boolean,
      default: false
    },
    disabled: {
      required: false,
      type: Boolean,
      default: false
    },
    fileList: {
      required: false,
      type: Array,
      default: () => []
    },
    nameShow: {
      required: false,
      type: Boolean,
      default: true
    },
    widthSize: {
      required: false,
      type: Number,
      default: 0
    },
    limit: {
      required: false,
      type: Number,
      default: 1
    },
    fileFilter: {
      required: false,
      type: Array,
      default: () => []
    },
    maxSize: {
      required: false,
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      dialogVisible: false,
      dialogImageUrl: '',
      nowFileList: [],
      key: [],
      filterImgType: ['jpg', 'jpeg', 'png', 'icon', 'gif', 'bmp', 'JPG', 'JPEG', 'PNG', 'ICON', 'GIF', 'BMP']
    }
  },
  mounted() {
    const arr = []
    this.fileList.forEach(item =>
      arr.push({
        url: item.url,
        name: item.url.split('.com/')[1],
        uid: 1
      })
    )
    this.nowFileList = JSON.parse(JSON.stringify(arr))
    this.key = JSON.parse(JSON.stringify(arr))
  },
  methods: {
    uploadBefore(file) {
      if (this.fileFilter.length > 0 && !this.fileFilter.find(item => file.file.type.indexOf(item) > -1)) {
        this.$refs.elUpload.uploadFiles = this.$refs.elUpload.uploadFiles.filter(item => item.uid !== file.file.uid)
        this.$message.error('上传文件格式不正确,请重新上传')
        return
      }
      if (this.maxSize !== 0 && file.file.size / 1024 / 1024 > this.maxSize) {
        this.$refs.elUpload.uploadFiles = this.$refs.elUpload.uploadFiles.filter(item => item.uid !== file.file.uid)
        this.$message.error(`文件最大上传${this.maxSize}M`)
        return
      }
      if (this.filterImgType.find(item => file.file.type.indexOf(item) > -1) && this.widthSize !== 0 && this.heightSize !== 0) {
        const _this = this
        new Promise(function(resolve, reject) {
          const _URL = window.URL || window.webkitURL
          var img = new Image()
          img.onload = function() {
            const valid = img.width <= _this.widthSize && img.height <= _this.heightSize
            valid ? resolve() : reject()
          }
          img.src = _URL.createObjectURL(file.file)
        }).then(() => {
          this.uploadFile(file)
        }, () => {
          this.$refs.elUpload.uploadFiles = this.$refs.elUpload.uploadFiles.filter(item => item.uid !== file.file.uid)
          this.$message.error(`上传图片分辨率为${this.widthSize}*${this.heightSize}`)
          return Promise.reject()
        })
      } else {
        this.uploadFile(file)
      }
    },
    uploadFile(file) {
      getPolicy({}, 'get').then(response => {
        const formData = new FormData()
        const pattern=/[`~!@#$^&*()=|{}':;',\\\[\]\.<>\/?~！@#￥……&*（）——|{}【】'；：""'。，、？\s]/g;
        // const name = response.dir  + new Date().getTime() + '_' + file.file.name.split('.')[0].replace(pattern,"")  + '.' + file.file.name.split('.')[1]
         const name = response.dir  + new Date().getTime() + '_' + file.file.name.slice(0,file.file.name.lastIndexOf('.')).replace(pattern,"")  + '.' + file.file.name.slice(file.file.name.lastIndexOf('.')+1)
        formData.append('policy', response.policy)
        formData.append('OSSAccessKeyId', response.accessId)
        formData.append('success_action_status', '200')
        formData.append('signature', response.signature)
        formData.append('key', name)
        formData.append('file', file.file)
        formData.append('type', file.file.type)
        if (response.callback !== null) {
          formData.append('callback', response.callback)
        }
        axios({
          url: response.host,
          method: 'POST',
          headers: { 'content-type': 'application/x-www-form-urlencoded' },
          data: formData
        }).then(res => {
          this.key.push({
            uid: file.file.uid,
            url: file.file.name, // 这个给商品素材用的
            name: name
          })
          this.$message.success('上传成功')
        })
          .catch(err => {
            this.$message.error(err.msg)
          })
      })
    },
    handleRemove(file) {
      this.key = this.key.filter(item => item.uid !== file.uid)
      this.nowFileList = JSON.parse(JSON.stringify(this.$refs.elUpload.uploadFiles))
      this.nowFileList = this.nowFileList.filter(item => item.uid !== file.uid)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>

<style lang="scss">
.mall-upload {
  .file-img {
    width: 100%;
  }
  .file-name {
    text-align: center;
    font-size: 12px;
    line-height: 16px;
  }
  .el-upload-list__item {
    overflow: initial;
    width: 150px;
    height: 150px;
    box-sizing: border-box;
    >div {
      height: 100%;
      width: 100%;
      img {
        height: 100%;
        width: 100%;
      }
    }
  }
  .notShow {
    .el-upload--picture-card {
      display: none;
    }
  }
}
</style>
